<?php
/***
 * 素材工具 Service
 *
 *
 * @author    lanhongjie <lanhj@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */

namespace App\Services\SourcePicService;


use App\Services\ImgServices\ImgTool;
use App\Services\Tool\GeneralTool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class SourcePicTool
{
    /**
     * 数据验证
     * @param Request $request
     * @param $check_data
     * @return mixed
     */
    public static function store(Request $request,$check_data)
    {
        $v = Validator::make($request->all(), $check_data);
        return $v;
    }

    /***
     * 查看素材是不是存在
     * @param $source_pic_id
     * @return bool|string
     */
    public  function sourcePicExistBySourcePicId($source_pic_id)
    {
        $source_pic_id=trim($source_pic_id);
        if(empty($source_pic_id)){
            return false;
        }
       $num=DB::table('source_pics')->where(array('state' => 1,'source_pic_id'=>$source_pic_id))
           ->count();
        return ($num==0)?false:true;
    }
    /***
     * 查看上传素材用户
     * @param $source_pic_id
     * @return null
     */
    public  function getSourcePicUserIdBySourcePicId($source_pic_id)
    {
        $source_pic_id=trim($source_pic_id);
        if(empty($source_pic_id)){
            return null;
        }
        $user_id=DB::table('source_pics')->where(array('state' => 1,'source_pic_id'=>$source_pic_id))
            ->value('user_id');
        return $user_id;
    }

    /***
     * 获取一条素材记录
     * @param $source_pic_id
     * @param int $type 1正常素材  其他包括伪删
     * @return null
     */
    public   function getSourcePicBySourcePicId($source_pic_id,$state=1)
    {
        $source_pic_id=trim($source_pic_id);
        if(empty($source_pic_id)){
            return null;
        }
        if($state===1){
            $source_pic=DB::table('source_pics')->where(array('state' => 1,'source_pic_id'=>$source_pic_id))
                ->select('is_infinite_stock','end_time','name as source_pic_name','is_infinite_time','source_pic_id','is_shelves','price as original_price','is_shelves','original_image','thumbnail','small_image','price as original_price','user_id','stock','audit_state')
                ->first();
        }else{
            $source_pic=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))
                ->select('is_infinite_stock','end_time','name as source_pic_name','is_infinite_time','source_pic_id','is_shelves','price as original_price','is_shelves','original_image','thumbnail','small_image','price as original_price','user_id','stock','audit_state')
                ->first();
        }
        return $source_pic;
    }

    /***
     * 素材版权判断
     * 创作判断素材是否可用，并获取素材主要信息
     * @param $source_pic_id
     * @param $product_temp_id
     * @param int $type 1创作的时候 2下单时
     * @return array
     */
    public function getSourcePicAvailableBySourcePicIdAndProdTempId($source_pic_id,$product_temp_id,$type=1)
    {
        $source_pic_id=trim($source_pic_id);
        $product_temp_id=trim($product_temp_id);
        if(empty($source_pic_id)||empty($product_temp_id)){
            return GeneralTool::createResult('','M03042');
        }
        if($type===1){
            $source_pic=DB::table('source_pics')->where(array(
                'state' => 1,
                'source_pic_id'=>$source_pic_id,
            ))->first();
        }else{
            $source_pic=DB::table('source_pics')->where(array(
                'source_pic_id'=>$source_pic_id,
            ))->first();
        }
        if(empty($source_pic)){
            $result=GeneralTool::createResult('','M03042');
            return $result;
        }
        $result=array();
        if($type===2){
            if($source_pic->auz_exp_time<=time()){
                $result=GeneralTool::createResult('','M03048');
            }else{
                $result=GeneralTool::createResult($source_pic,'M00000');
            }
            return $result;
        }
        if ($source_pic->auz_exp_time<=time()){
            $result=GeneralTool::createResult('','M03048');
        }elseif ($source_pic->audit_state==3){
            $result=GeneralTool::createResult('','M03045');
        }elseif ($source_pic->audit_state==1){
            $result=GeneralTool::createResult('','M03044');
        }else{
            $result=GeneralTool::createResult($source_pic,'M00000');
        }
        if($type==1&&($source_pic->is_shelves!=1)){
            $result=GeneralTool::createResult('','M03043');
        }
        return $result;
    }

    /***
     * 静态判断当前模板对此素材是否有权限
     * @param $source_pic_id
     * @param $product_temp_id
     * @param int $type
     * @return array
     */
    public static function getSourcePicAvailableStateFuncBySourcePicIdAndProdTempId($source_pic_id,$product_temp_id,$type=1)
    {
        $source_pic_id=trim($source_pic_id);
        $product_temp_id=trim($product_temp_id);
        if(empty($source_pic_id)||empty($product_temp_id)){
            return GeneralTool::createResult('','M03042');
        }
        if($type===1){
            $source_pic=DB::table('source_pics')->where(array(
                'state' => 1,
                'source_pic_id'=>$source_pic_id,
            ))->first();
        }else{
            $source_pic=DB::table('source_pics')->where(array(
                'source_pic_id'=>$source_pic_id,
            ))->first();
        }
        if(empty($source_pic)){
            $result=GeneralTool::createResult('','M03042');
            return $result;
        }
        $result=array();
        if($type===2){
            if($source_pic->auz_exp_time<=time()){
                $result=GeneralTool::createResult('','M03048');
            }else{
                $result=GeneralTool::createResult($source_pic,'M00000');
            }
            return $result;
        }
        if ($source_pic->auz_exp_time<=time()){
            $result=GeneralTool::createResult('','M03048');
        }elseif ($source_pic->is_shelves!=1){
            $result=GeneralTool::createResult('','M03043');
        }elseif ($source_pic->audit_state==3){
            $result=GeneralTool::createResult('','M03045');
        }elseif ($source_pic->audit_state==1){
            $result=GeneralTool::createResult('','M03044');
        }else{
            $result=GeneralTool::createResult($source_pic,'M00000');
        }
        return $result;
    }
    /****
     * 获取订单中素材明细
     * @param $source_pic_id
     * @return null
     */
    public  static function getSourcePicDetail($source_pic_id)
    {
        $source_pic_id=trim($source_pic_id);
        if(empty($source_pic_id)){
            return null;
        }
        $source_pic=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))
            ->select('source_pic_id','is_infinite_time','end_time','small_image as thumbnail','price as original_price','user_id','name as source_pic_name')
            ->first();
        if(!empty($source_pic)){
            if(!empty($source_pic->thumbnail)){
                $thumbnail=ImgTool::getImgUrlByImgPath($source_pic->thumbnail);
                $source_pic->thumbnail=empty($thumbnail)?'':$thumbnail;
            }
            $source_pic->preferential_price=$source_pic->original_price;
            $source_pic->type=2;
        }
        return $source_pic;
    }
    /****
     * 获取素材主表上的价格
     * @param $source_pic_id
     * @return bool
     */
    public static function getSourcePicPrice($source_pic_id,$state=1)
    {
        if(empty($source_pic_id)){
            return false;
        }
        if($state===1){
            $price= DB::table('source_pics')->where(array('state'=>$state,'source_pic_id'=>$source_pic_id))
                ->value('price');
        }else{
            $price= DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))
                ->value('price');
        }
        return ($price===null)?false:$price;
    }
    /***
     * 判断标签是不是已经存在
     * @param $tag_name
     * @return bool
     */
    public function checkTagNameExist($tag_name){
        $tag_name=trim($tag_name);
        if(empty($tag_name)){
            return false;
        }
        $num=DB::table('tags')->where(array('state'=>1,'name'=>$tag_name))->count();
        return ($num==0)?false:true;
    }

    /***
     * 获取Tag记录
     * @param $tag_id
     * @return null
     */
    public function getTagByTagId($tag_id){
        if(empty($tag_id)){
            return null;
        }
        $tag=DB::table('tags')->where(array('state'=>1,'id'=>$tag_id))->first();
        return $tag;
    }
    //增加库存
    public static function incrementStock($source_pic_id,$num=1){
        if(empty($source_pic_id)){
            return 'M03026';
        }
        if(!is_int($num)||($num<0)){
            return 'M03041';
        }
        $is_infinite_stock=self::isInfiniteStock($source_pic_id);
        if($is_infinite_stock==1){
            return 'M00000';
        }
        self::updateSourcePicStock($source_pic_id,$num);
        return 'M00000';
    }

    /***
     * 减少库存
     * @param $source_pic_id
     * @param int $num
     * @return string
     */
    public static function decrementStock($source_pic_id,$num=1){
        if(empty($source_pic_id)){
            return 'M03026';
        }
        if(!is_int($num)||($num>0)){
            return 'M03041';
        }
        $is_infinite_stock=self::isInfiniteStock($source_pic_id);
        if($is_infinite_stock==1){
            return 'M00000';
        }
        self::updateSourcePicStock($source_pic_id,-$num);
        return 'M00000';
    }
    /****
     * 查看素材是不是无限库存
     * @param $source_pic_id
     * @return string
     */
    public static function isInfiniteStock($source_pic_id){
        if(empty($source_pic_id)){
            return 'M03026';
        }
        $is_infinite_stock=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))->value('is_infinite_stock');
        return $is_infinite_stock;
    }
    /***
     * 添加素材已售
     * @param $source_pic_id
     * @return string
     */
    public static function updateSourcePicUsedNum($source_pic_id,$num=1){
        if(empty($source_pic_id)){
            return 'M03026';
        }
        if(!is_int($num)){
            return 'M03040';
        }
        $used_num=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))->value('used_num');
        if(is_int($used_num)&&($num>=0)){
            $used_num+=$num;
        }elseif(is_int($used_num)&&($num<0)&&($used_num+$num>=0)){
            $used_num+=$num;
        }else{
            return 'M00001';
        }
        $res=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))->update(array(
            'updated_at'=>time(),
            'used_num'=>$used_num,
        ));
        return $res;
    }

    /***
     * 更新库存
     * @param $source_pic_id
     * @param int $num
     * @return string
     */
    public static function updateSourcePicStock($source_pic_id,$num=1){
        if(empty($source_pic_id)){
            return 'M03026';
        }
        if(!is_int($num)){
            return 'M03040';
        }
        $stock=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))->value('stock');
        if(is_int($stock)&&($num>=0)){
            $stock+=$num;
        }elseif(is_int($stock)&&($num<0)&&($stock+$num>=0)){
            $stock+=$num;
        }else{
            return 'M00001';
        }
        $res=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))->update(array(
            'updated_at'=>time(),
            'stock'=>$stock,
        ));
        return $res;
    }
    /***
     * 减素材库存数
     * @param $source_pic_id
     * @return bool
     */
    private static function decrementStockInDB($source_pic_id){
        if(empty($source_pic_id)){
            return false;
        }
        $res=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))->decrement('stock');
        return ($res===1)?true:false;
    }

    /***
     * 判断素材有没有库存
     * 暂时只要数据库不是真删除素材都认为素材有库存
     * @param $source_pic_id
     * @return string
     */
    public static function hasStock($source_pic_id){
        if(empty($source_pic_id)){
            return 'M03026';
        }
        $has_source_pic=self::hasSourcePic($source_pic_id,2);
        return ($has_source_pic)?'M00000':'M03030';
    }

    /***
     * 暂时只要数据库不是真删除素材都认为素材有库存
     * @param $source_pic_id
     * @return array|string
     */
    public static function getStock($source_pic_id){
        if(empty($source_pic_id)){
            return array();
        }
        $has_source_pic=self::hasSourcePic($source_pic_id,2);
        if($has_source_pic===false){
            return array();
        }else{
            return array('is_infinite_stock'=>1,'stock'=>0);
        }
    }
    /***
     * 判断数据库中有没有存储过素材
     * @param $source_pic_id
     * @param int $type
     * @return bool
     */
    public static function hasSourcePic($source_pic_id,$type=1){
        if(empty($source_pic_id)){
            return false;
        }
        if($type===1){
            $num=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id,'state'=>1))
                ->count();
        }else{
            $num=DB::table('source_pics')->where(array('source_pic_id'=>$source_pic_id))
                ->count();
        }
        return ($num>0)?true:false;
    }
    /**
     * 获取用户类型
     */
    public static function getUserType($user_id)
    {
        if(!is_int($user_id)){
            return false;
        }
        $user_type = DB::table('users')->where('user_id', $user_id)->value('user_type');
        return $user_type;
    }

    /***
     * 审核状态码对应审核信息
     * @param $audit_state
     * @return string
     */
    public static function getAuditByAuditState($audit_state)
    {
        if(!is_int($audit_state)){
            return '';
        }
        $audit='';
        switch ($audit_state)
        {
            case 1:
                $audit='审核中';
            break;
            case 2:
                $audit='已通过';
                break;
            case 3:
                $audit='未通过';
                break;
            default:
                $audit='未提交';
                break;
        }
        return $audit;
    }

    /***
     * 上架状态转换成上架状态值
     * @param $is_shelves
     * @return string
     */
    public static function getIsShelvesState($is_shelves,$audit_state=1)
    {
        if(!is_int($is_shelves)){
            return '';
        }
        if($audit_state!=2){
            return '已下架';
        }
        switch ($is_shelves)
        {
            case 1:
                $shelves='已上架';
                break;
            default:
                $shelves='已下架';
                break;
        }
        return $shelves;
    }

    /***
     * 用户下架素材
     * @param $user_id
     * @return bool
     */
    public static function offShelvesSourcePicByUserId($user_id)
    {
        try{
            if(!is_int($user_id)||empty($user_id)){
                return false;
            }
            Log::info('用户ID为:'.$user_id.',下架素材');
            $res=DB::table('source_pics')->where(array(
                'state'=>1,
                'user_id'=>$user_id,
                'is_shelves'=>1))->update(array(
                'updated_at'=>time(),
                'is_shelves'=>0,
            ));
            return empty($res)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    /***
     * 获取最顶级Tag_id
     * @param $tag_id
     * @return int|null
     */
    public static function getTopTagIdByTagId($tag_id)
    {
        if(empty($tag_id)||!is_int($tag_id)){
            return null;
        }
        $top_tag_id=$tag_id;
        $p_tag_id=$tag_id;
        do {
            $top_tag_id=$p_tag_id;
            $p_tag_id=self::getParentsTagIdByTagId($p_tag_id);
        } while (!empty($p_tag_id));
       return $top_tag_id;
    }

    /***
     * 获取父级Tag_id
     * @param $tag_id
     * @return null
     */
    private static function getParentsTagIdByTagId($tag_id)
    {
         if(empty($tag_id)||!is_int($tag_id)){
             return null;
         }
        $p_tag_id=DB::table('tags')->where(array('id'=>$tag_id,'state'=>1))
            ->value('pid');
        return ($p_tag_id===0)?null:$p_tag_id;
    }
    /***
     * @param $result
     * @param $message
     * @param $state
     * @return array
     */
    public static function createResult($result,$message,$state){
        return array('message'=>$message,'result'=>($result==""?(object)array():$result),'state'=>$state);
    }

    /***
     * 更新素材单价
     * @param $source_pic_id
     * @param $price
     * @return bool
     */
    public static function updateSourcePicPrice($source_pic_id,$price,$state=0){
        if(empty($source_pic_id)||!is_numeric($price)){
            return false;
        }
        $price=floatval($price);
        $query=DB::table('source_pics')->where(array(
            'source_pic_id'=>$source_pic_id,
        ));
        if($state===1){
            $query->where('state',1);
        }
        $update_res=$query->update(array(
            'price'=>$price,
            'updated_at'=>time(),
        ));
        return ($update_res>0)?true:false;
    }

    /***
     * 定时下架素材
     * @return bool
     */
    public static function sourcePicOffTheShelf(){
        try{
            $ids=DB::table('source_pics')->where(array(
                'is_infinite_time'=>0,
                'state'=>1,
                'is_shelves'=>1,
            ))->where('end_time','<=',time())
                ->pluck('id')
                ->toArray();
            Log::info('******************定时下架超时素材 *******************');
            if(empty($ids)){
                return true;
            }
            Log::info($ids);
            foreach ($ids as $id){
                DB::table('source_pics')->where(array(
                    'id'=>$id,
                    'state'=>1,
                ))->update(array(
                    'updated_at'=>time(),
                    'is_shelves'=>0,
                ));
            }
            return true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 获取所有的素材Id
     * @param int $state
     * @return array
     */
    public static function getAllSourcePicIds($state=1){
        if(!is_int($state)){
            return array();
        }
        $query=DB::table('source_pics');
        if($state==1){
            $query->where('state',1);
        }
        $source_pic_ids=$query->pluck('source_pic_id')
            ->toArray();
        return empty($source_pic_ids)?array():$source_pic_ids;
    }
}